package com.ksyun.alert.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ksyun.alert.constant.RedisStreamConstant;
import com.ksyun.alert.dto.MetricDTO;
import com.ksyun.alert.dto.MetricQueryDataRespDTO;
import com.ksyun.alert.dto.MetricQueryReqDTO;
import com.ksyun.alert.dto.MetricQueryRespDTO;
import com.ksyun.alert.entity.MonitorDatasDO;
import com.ksyun.alert.service.IMetricService;
import com.ksyun.alert.service.MonitorDatasService;
import com.ksyun.alert.utils.RequestIdUtil;
import com.ksyun.alert.utils.TimestampConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Zhang
 * @date 2024-04-30
 */
@Service
@Slf4j
public class IMetricServiceImpl implements IMetricService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private MonitorDatasService monitorDatasService;

    @Override
    public void write2Db(List<MetricDTO> metricList) {
        if (metricList == null || metricList.isEmpty()) {
            return;
        }
        //按时间戳对指标列表进行分组
        Map<Long, List<MetricDTO>> hashMap = metricList.stream().collect(Collectors.groupingBy(MetricDTO::getTimestamp));
        hashMap.forEach((key, value) -> {
            write2Redis(value);
            write2Mysql(value);
        });
    }

    @Override
    public MetricQueryRespDTO queryMetricsByPeriodAndReqId(MetricQueryReqDTO metricQueryReqDTO) {
        LambdaQueryWrapper<MonitorDatasDO> queryWrapper = Wrappers.lambdaQuery(MonitorDatasDO.class)
//                .eq(MonitorDatasDO::getRequestId, Long.parseLong(metricQueryReqDTO.getRequestId()))
                .ge(MonitorDatasDO::getTimestamp, TimestampConverter.stringToTimestamp(metricQueryReqDTO.getStart()))
                .le(MonitorDatasDO::getTimestamp, TimestampConverter.stringToTimestamp(metricQueryReqDTO.getEnd()));
        List<MonitorDatasDO> monitorDatasDOList = monitorDatasService.list(queryWrapper);
        List<MetricQueryDataRespDTO> data = monitorDatasDOList.stream()
                                                                .map(monitorDatasDO -> MetricQueryDataRespDTO.builder()
                                                                            .metric(monitorDatasDO.getMetricName())
                                                                            .timestamp((monitorDatasDO.getTimestamp().intValue()))
                                                                            .value(monitorDatasDO.getValue())
                                                                            .build())
                                                                .collect(Collectors.toList());

        return MetricQueryRespDTO.builder()
                .total(monitorDatasDOList.size())
                .requestId(metricQueryReqDTO.getRequestId())
                .data(data)
                .build();
    }

    /**
     * 向redis的Stream写数据（可以理解为向交换机写数据）
     * 此key用处不大，因为我们需要的是value的值，即metricList的JSON序列化结果jsonString用于计算
     * 命令：xadd STREAM_NAME * key jsonString
     */
    private void write2Redis(List<MetricDTO> metricList) {
        String jsonString = JSON.toJSONString(metricList);
        String key = RedisStreamConstant.WRITE_JSON_KEY;
        RecordId recordId = stringRedisTemplate.opsForStream().add(StreamRecords.newRecord()
                .ofObject(keyValuePair(key, jsonString))
                .withStreamKey(RedisStreamConstant.STREAM_NAME));
    }

    /**
     * 向MySQL的指标记录表写入所有指标数据
     */
    private void write2Mysql(List<MetricDTO> metricList) {
        List<MonitorDatasDO> collect = metricList.stream().map(metricDTO -> MonitorDatasDO.builder()
                .requestId(Long.valueOf(RequestIdUtil.getRequestId()))
                .timestamp(Long.valueOf(String.valueOf(metricDTO.getTimestamp())))
                .metricName(metricDTO.getMetric())
                .value(metricDTO.getValue())
                .hostName(metricDTO.getTags().get("hostname"))
                .build()).collect(Collectors.toList());
        monitorDatasService.saveBatch(collect);
    }

    private Map<String, String> keyValuePair(String key, String value) {
        Map<String, String> map = new HashMap<>();
        map.put(key, value);
        return map;
    }
}
